package com.codename1.samples;


import com.codename1.db.Cursor;
import com.codename1.db.Database;
import com.codename1.db.Row;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.io.Util;
import com.codename1.ui.Command;
import com.codename1.ui.FontImage;
import com.codename1.ui.TextArea;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.table.DefaultTableModel;
import com.codename1.ui.table.Table;
import com.codename1.ui.plaf.Style;
import java.util.ArrayList;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename
 * One</a> for the purpose of building native mobile applications using Java.
 */
public class SQLExplorerSample {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if (err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });
    }

    public void start() {
        if (current != null) {
            current.show();
            return;
        }
        Toolbar.setGlobalToolbar(true);
        Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
        FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_QUERY_BUILDER, s);
        Form hi = new Form("SQL Explorer", new BorderLayout());
        hi.getToolbar().addCommandToRightBar("", icon, (e) -> {
            TextArea query = new TextArea(3, 80);
            Command ok = new Command("Execute");
            Command cancel = new Command("Cancel");
            if (Dialog.show("Query", query, ok, cancel) == ok) {
                Database db = null;
                Cursor cur = null;
                try {
                    db = Display.getInstance().openOrCreate("MyDB.db");
                    if (query.getText().startsWith("select")) {
                        cur = db.executeQuery(query.getText());
                        int columns = cur.getColumnCount();
                        hi.removeAll();
                        if (columns > 0) {
                            boolean next = cur.next();
                            if (next) {
                                ArrayList<String[]> data = new ArrayList<>();
                                String[] columnNames = new String[columns];
                                for (int iter = 0; iter < columns; iter++) {
                                    columnNames[iter] = cur.getColumnName(iter);
                                }
                                while (next) {
                                    Row currentRow = cur.getRow();
                                    String[] currentRowArray = new String[columns];
                                    for (int iter = 0; iter < columns; iter++) {
                                        currentRowArray[iter] = currentRow.getString(iter);
                                    }
                                    data.add(currentRowArray);
                                    next = cur.next();
                                }
                                Object[][] arr = new Object[data.size()][];
                                data.toArray(arr);
                                hi.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
                            } else {
                                hi.add(BorderLayout.CENTER, "Query returned no results");
                            }
                        } else {
                            hi.add(BorderLayout.CENTER, "Query returned no results");
                        }
                    } else {
                        db.execute(query.getText());
                        hi.add(BorderLayout.CENTER, "Query completed successfully");
                    }
                    hi.revalidate();
                } catch (IOException err) {
                    Log.e(err);
                    hi.removeAll();
                    hi.add(BorderLayout.CENTER, "Error: " + err);
                    hi.revalidate();
                } finally {
                    Util.cleanup(db);
                    Util.cleanup(cur);
                }
            }
        });
        hi.show();
    }

    public void stop() {
        current = getCurrentForm();
        if (current instanceof Dialog) {
            ((Dialog) current).dispose();
            current = getCurrentForm();
        }
    }

    public void destroy() {
    }

}
